package com.changyou.kf.common.config;

import com.alibaba.fastjson2.JSONFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.logging.LoggingSystemProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

import java.lang.management.ManagementFactory;

@Slf4j
@Configuration
public class ApplicationAutoConfiguration {

    @Order(value = Ordered.HIGHEST_PRECEDENCE)
    @Bean
    public ApplicationRunner applicationRunner(Environment environment) {
        // global set fastjson ignore jackson annotation
        JSONFactory.setUseJacksonAnnotation(false);

        return args -> {

            String applicationName = System.getProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName());
            String pid = System.getProperty(LoggingSystemProperty.PID.getEnvironmentVariableName());

            System.out.println("ApplicationRunner...");

            System.out.println("ApplicationRunner applicationName:" + applicationName);
            System.out.println("ApplicationRunner pid:" + pid);

            /*String pid = System.getProperty("PID");
            String port = environment.getProperty("server.port");
            String javaVersion = System.getProperty("java.version");
            String userName = System.getProperty("user.name");
            String userDir = System.getProperty("user.dir");

            String serverip = NetUtils.getServerip();
            System.setProperty(GlobalConstants.HOSTNAME, serverip);
            System.setProperty("server.port", port);
            System.setProperty("server.name", environment.getProperty("spring.application.name"));
            System.setProperty("server.version", environment.getProperty("info.version"));*/

            StringBuilder message = new StringBuilder();
            /*message.append(LocalDateTime.now()
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
            message.append(" [main] INFO Started using Java ").append(javaVersion)
                    .append(" on ").append(serverip).append(":").append(port)
                    .append(" with PID ").append(pid)
                    .append(" by ").append(userName)
                    .append(" in ").append(userDir);*/
            try {
                double uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0;
                message.append(" (JVM running for ").append(uptime).append(")");
            } catch (Throwable ex) {
                // No JVM time available
            }
            System.out.println(message.toString());
            // Started K8sApplication in 13.965 seconds (JVM running for 17.081)
        };
    }
}
